﻿using DevExpress.XtraEditors;
using DevExpress.XtraLayout;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using System.Collections.Generic;
using System.Windows.Forms;
using WorkflowCore2210A.Domain.Model;
using WorkflowCore2210A.Application.Dto.Input;
using System.ComponentModel;
using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using B.MESUI.Login.EquipmentManagement.DTO;
using DevExpress.XtraEditors.Repository;
using System.Linq;
using DevExpress.Internal;
using Standard;
using RBAC_Application.Dto.Output;


namespace B.MESUI.Login.WorkflowCore.Definition
{
    public partial class AddDefinition : DevExpress.XtraEditors.XtraForm
    {
        // 主信息控件
        private TextEdit txtTitle;
        private TextEdit txtDefinitionId;
        private SpinEdit spinVersion;

        // 步骤节点表格
        private GridControl gridSteps;
        private GridView gridViewSteps;

        // 数据模型
        private WorkflowDefinitionInput model;

        private bool isRefreshing = false;


        private RepositoryItemLookUpEdit repositoryItemLookUpEditUser;


        private List<User> userList = new List<User>
        {
            // ... 其他用户 ...
        };

        public AddDefinition()
        {
            InitializeComponent();
            InitUI();
            InitData();
            this.CenterToParent();
        }

        private void InitUI()
        {
            // 主布局
            var layout = new LayoutControl { Dock = DockStyle.Top, Height = 120 };

            txtTitle = new TextEdit();
            txtDefinitionId = new TextEdit();
            spinVersion = new SpinEdit();
            spinVersion.Properties.MinValue = 1;
            spinVersion.Properties.MaxValue = 1000;
            spinVersion.Value = 1;
            spinVersion.Properties.Mask.EditMask = "N0"; // 只允许整数
            spinVersion.Properties.Mask.UseMaskAsDisplayFormat = true;

            layout.AddItem("流程设计标题", txtTitle);
            layout.AddItem("流程设计标识", txtDefinitionId);
            layout.AddItem("版本号", spinVersion);

            // 步骤节点表格
            gridSteps = new GridControl { Dock = DockStyle.Fill };
            gridViewSteps = new GridView();
            gridSteps.MainView = gridViewSteps;
            gridSteps.ViewCollection.Add(gridViewSteps);

            // 步骤相关列
            gridViewSteps.Columns.AddVisible("StepId", "步骤ID");
            gridViewSteps.Columns.AddVisible("StepName", "步骤名称");
            gridViewSteps.Columns.AddVisible("NextStepId", "下一个步骤ID");

            // 新增审批人列
            var colAuditUser = gridViewSteps.Columns.AddVisible("AuditUserId", "审批人");
            repositoryItemLookUpEditUser = new RepositoryItemLookUpEdit();
            repositoryItemLookUpEditUser.DataSource = userList;
            repositoryItemLookUpEditUser.DisplayMember = "Name";
            repositoryItemLookUpEditUser.ValueMember = "Id";
            repositoryItemLookUpEditUser.NullText = "请选择";
            repositoryItemLookUpEditUser.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;

            // 只显示姓名，不显示ID
            repositoryItemLookUpEditUser.Columns.Clear();
            repositoryItemLookUpEditUser.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "审批人姓名"));
            colAuditUser.ColumnEdit = repositoryItemLookUpEditUser;

            // 隐藏ID和NextStepId
            gridViewSteps.Columns["StepId"].Visible = false;
            gridViewSteps.Columns["NextStepId"].Visible = false;

            // 自动列宽铺满
            gridViewSteps.OptionsView.ColumnAutoWidth = true;

            // 添加控件到窗体
            this.Controls.Add(gridSteps);
            this.Controls.Add(layout);

            // 窗体属性
            this.Text = "流程设计编辑";
            // 3. 事件绑定
            gridViewSteps.RowUpdated += (s, e) => RefreshStepIds();
            gridViewSteps.RowDeleted += (s, e) => RefreshStepIds();
            gridViewSteps.RowCountChanged += (s, e) => RefreshStepIds();
            gridViewSteps.CellValueChanged += gridViewSteps_CellValueChanged;

            var btnSave = new SimpleButton
            {
                Text = "保存",
                Size = new System.Drawing.Size(80, 30),
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            // 设置按钮位置（右下角，距离右边和下边各20像素）
            btnSave.Location = new System.Drawing.Point(this.ClientSize.Width - btnSave.Width - 20, this.ClientSize.Height - btnSave.Height - 20);

            // 让按钮随窗体大小变化自动保持右下角
            this.Controls.Add(btnSave);
            btnSave.BringToFront();

            // 注册事件
            btnSave.Click += BtnSave_Click;

            // 让按钮随窗体大小变化自动调整位置
            this.Resize += (s, e) =>
            {
                btnSave.Location = new System.Drawing.Point(this.ClientSize.Width - btnSave.Width - 20, this.ClientSize.Height - btnSave.Height - 20);
            };


        }


        private void RefreshStepIds()
        {
            if (isRefreshing) return; // 防止递归
            isRefreshing = true;

            var list = gridSteps.DataSource as BindingList<StepNode>;
            if (list == null || list.Count == 0)
            {
                isRefreshing = false;
                return;
            }

            for (int i = 0; i < list.Count; i++)
            {
                list[i].StepId = (i + 1).ToString();
                list[i].NextStepId = (i == list.Count - 1) ? "EndStep" : (i + 2).ToString();
            }
            // 不要调用 gridViewSteps.RefreshData();

            isRefreshing = false;
        }


        // 行更新后
        private void gridViewSteps_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            RefreshStepIds();
        }

        // 行删除后
        private void gridViewSteps_RowDeleted(object sender, EventArgs e)
        {
            RefreshStepIds();
        }

        // 新增行后（可选）
        private void gridViewSteps_RowCountChanged(object sender, EventArgs e)
        {
            RefreshStepIds();
        }


        private void InitData()
        {
            // 初始化数据模型
            model = new WorkflowDefinitionInput
            {
                Title = "",
                DefinitionId = "",
                Version = 1,
                Steps = new BindingList<StepNode>
                {
                    new  StepNode { StepId = "1", StepName = "开始", NextStepId = "2", AuditUserId = 1001, AuditUserName = "张三" }
                }
            };

            // 绑定主信息
            txtTitle.DataBindings.Add("EditValue", model, "Title");
            txtDefinitionId.DataBindings.Add("EditValue", model, "DefinitionId");
            spinVersion.DataBindings.Add("EditValue", model, "Version");

            // 绑定步骤节点表格
            gridSteps.DataSource = model.Steps;
            // 允许新增行
            gridViewSteps.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            // 允许编辑
            gridViewSteps.OptionsBehavior.Editable = true;
            // 绑定
            gridSteps.DataSource = model.Steps;
            // 4. 初始化后刷新
            RefreshStepIds();
        }

        private async void BtnSave_Click(object sender, EventArgs e)
        {
            gridViewSteps.CloseEditor();
            gridViewSteps.UpdateCurrentRow();

            // 组装数据
            model.Title = txtTitle.Text;
            model.DefinitionId = txtDefinitionId.Text;
            model.Version = (int)spinVersion.Value;

            // 步骤数据已自动同步到 model.Steps

            // 序列化为 JSON
            string json = JsonConvert.SerializeObject(model);

            // 发送 POST 请求
            string apiUrl = $"{BaseUrl.WorkflowUrl}Workflow/AddWorkflowDefinition"; // 替换为你的接口地址
            using (var client = new HttpClient())
            {
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                try
                {
                    var response = await client.PostAsync(apiUrl, content);
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("保存成功！");
                    }
                    else
                    {
                        string resp = await response.Content.ReadAsStringAsync();
                        MessageBox.Show("保存失败：" + resp);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("请求异常：" + ex.Message);
                }
            }
            this.DialogResult = DialogResult.OK; // 关闭窗口并返回OK
            this.Close();
        }

        // 监听单元格值变化事件，自动赋值姓名
        private void gridViewSteps_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "AuditUserId")
            {
                var row = gridViewSteps.GetRow(e.RowHandle) as StepNode;
                if (row != null)
                {
                    var user = userList.FirstOrDefault(u => u.Id.Equals(row.AuditUserId));
                    row.AuditUserName = user?.Name ?? "";
                    gridViewSteps.RefreshRow(e.RowHandle);
                }
            }
        }

        private async void AddDefinition_Load(object sender, EventArgs e)
        {
            using (HttpClient _httpClient = new HttpClient())
            {
                var response3 = await _httpClient.GetAsync($"http://39.103.49.30:8972/api/User");
                var json3 = await response3.Content.ReadAsStringAsync();
                var list3 = JsonConvert.DeserializeObject<ApiResult<List<UserDto>>>(json3);
                foreach (var item in list3.ResultData) 
                {
                    userList.Add(new User { Id = item.Id, Name = item.UserName });
                }
            }
        }
    }

    public class User
    {
        public long Id { get; set; }
        public string Name { get; set; }
    }
}